#!/bin/bash

# ========================================
# XRK-Yunzai 一键重装脚本
# 版本: 5.0 | 特点: 解决依赖问题 | 跳过错误包 | 不动Node.js
# ========================================

set +e  # 关闭错误退出，让脚本继续执行

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}   XRK-Yunzai 重装脚本              ${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""

# 检查权限
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}✗ 需要root权限${NC}"
    echo "用: sudo $0"
    exit 1
fi

# 解决dpkg依赖问题
fix_dpkg_issues() {
    echo -e "${YELLOW}[1/8] 修复dpkg依赖问题...${NC}"
    
    # 1. 先清理锁文件
    echo -e "${BLUE}清理锁文件...${NC}"
    rm -f /var/lib/dpkg/lock /var/lib/dpkg/lock-frontend 2>/dev/null
    rm -f /var/cache/apt/archives/lock 2>/dev/null
    
    # 2. 跳过有问题的包
    echo -e "${BLUE}跳过有问题的包...${NC}"
    
    # 备份dpkg状态
    cp /var/lib/dpkg/status /var/lib/dpkg/status.backup
    
    # 移除humanity-icon-theme包的配置状态，让它保持未配置状态
    if dpkg -l | grep -q "^iF.*humanity-icon-theme"; then
        echo -e "${YELLOW}跳过有问题的包: humanity-icon-theme${NC}"
        dpkg --remove --force-remove-reinstreq humanity-icon-theme 2>/dev/null || \
        dpkg --purge --force-remove-reinstreq humanity-icon-theme 2>/dev/null
    fi
    
    # 3. 修复依赖
    echo -e "${BLUE}修复损坏的包...${NC}"
    apt-get install -f -y 2>&1 | grep -v "humanity-icon-theme"
    
    # 4. 配置所有包
    echo -e "${BLUE}配置所有包...${NC}"
    dpkg --configure -a 2>&1 | grep -v "humanity-icon-theme"
    
    echo -e "${GREEN}✓ dpkg问题修复完成${NC}"
}

# 设置源
setup_sources() {
    echo -e "${YELLOW}[2/8] 设置软件源...${NC}"
    
    # 备份原源
    cp /etc/apt/sources.list /etc/apt/sources.list.bak 2>/dev/null
    
    # 使用简单的阿里云源
    cat > /etc/apt/sources.list << 'EOF'
deb http://mirrors.aliyun.com/ubuntu/ focal main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ focal-security main restricted universe multiverse
EOF
    
    # 安静更新
    apt-get update -qq 2>/dev/null
    
    echo -e "${GREEN}✓ 源设置完成${NC}"
}

# 清理旧浏览器
clean_browsers() {
    echo -e "${YELLOW}[3/8] 清理浏览器...${NC}"
    
    # 停止进程
    pkill -9 chromium 2>/dev/null || true
    pkill -9 chrome 2>/dev/null || true
    pkill -9 google-chrome 2>/dev/null || true
    
    # 卸载浏览器包
    apt-get remove --purge -y chromium-browser chromium google-chrome-stable google-chrome 2>/dev/null || true
    
    # 清理配置
    rm -rf ~/.config/chromium ~/.config/google-chrome 2>/dev/null
    rm -rf ~/.cache/chromium ~/.cache/google-chrome 2>/dev/null
    
    # 清理系统
    apt-get autoremove -y 2>/dev/null
    apt-get clean 2>/dev/null
    
    echo -e "${GREEN}✓ 浏览器清理完成${NC}"
}

# 安装Chromium依赖
install_chromium_deps() {
    echo -e "${YELLOW}[4/8] 安装Chromium依赖...${NC}"
    
    # 安装核心依赖（跳过任何错误）
    for package in libnss3 libxss1 libasound2 libatk-bridge2.0-0 libgtk-3-0 libgbm1; do
        apt-get install -y --no-install-recommends "$package" 2>/dev/null || \
        echo -e "${YELLOW}跳过包: $package${NC}"
    done
    
    echo -e "${GREEN}✓ 依赖安装完成${NC}"
}

# 安装Chromium
install_chromium() {
    echo -e "${YELLOW}[5/8] 安装Chromium...${NC}"
    
    # 尝试安装chromium-browser
    if apt-get install -y chromium-browser 2>/dev/null; then
        echo -e "${GREEN}✓ Chromium安装成功${NC}"
        return 0
    fi
    
    # 尝试安装chromium
    if apt-get install -y chromium 2>/dev/null; then
        echo -e "${GREEN}✓ Chromium安装成功${NC}"
        return 0
    fi
    
    # 下载Chrome
    echo -e "${YELLOW}下载Chrome...${NC}"
    
    ARCH=$(dpkg --print-architecture)
    TEMP_DIR=$(mktemp -d)
    cd "$TEMP_DIR"
    
    if [ "$ARCH" = "amd64" ]; then
        wget -q --tries=2 --timeout=30 "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"
    elif [ "$ARCH" = "arm64" ]; then
        wget -q --tries=2 --timeout=30 "https://dl.google.com/linux/direct/google-chrome-stable_current_arm64.deb"
    fi
    
    if ls *.deb 2>/dev/null; then
        dpkg -i *.deb 2>/dev/null || apt-get install -f -y 2>/dev/null
        echo -e "${GREEN}✓ Chrome安装成功${NC}"
    else
        echo -e "${RED}✗ 下载失败${NC}"
    fi
    
    cd /
    rm -rf "$TEMP_DIR"
}

# 检查并修复Chromium安装
verify_chromium() {
    echo -e "${YELLOW}[6/8] 验证Chromium...${NC}"
    
    if command -v chromium-browser >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Chromium-browser: $(chromium-browser --version 2>/dev/null | head -1)${NC}"
    elif command -v chromium >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Chromium: $(chromium --version 2>/dev/null | head -1)${NC}"
    elif command -v google-chrome >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Google Chrome: $(google-chrome --version 2>/dev/null | head -1)${NC}"
    else
        echo -e "${RED}✗ 未找到浏览器${NC}"
        return 1
    fi
    
    return 0
}

# 修复Puppeteer
fix_puppeteer() {
    echo -e "${YELLOW}[7/8] 修复Puppeteer...${NC}"
    
    # 检查Node.js
    if ! command -v node >/dev/null 2>&1; then
        echo -e "${RED}✗ Node.js未安装，跳过${NC}"
        return 1
    fi
    
    # 检查项目目录
    if [ ! -d "/root/XRK-Yunzai" ]; then
        echo -e "${RED}✗ 项目目录不存在，跳过${NC}"
        return 1
    fi
    
    cd "/root/XRK-Yunzai"
    
    # 设置镜像
    npm config set registry https://registry.npmmirror.com 2>/dev/null
    
    # 清理
    rm -rf node_modules/puppeteer 2>/dev/null
    rm -rf ~/.cache/puppeteer 2>/dev/null
    
    # 设置环境变量
    export PUPPETEER_SKIP_DOWNLOAD=true
    export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
    
    # 获取chromium路径
    CHROMIUM_PATH=$(command -v chromium-browser || command -v chromium || command -v google-chrome || echo "")
    if [ -n "$CHROMIUM_PATH" ]; then
        export PUPPETEER_EXECUTABLE_PATH="$CHROMIUM_PATH"
    fi
    
    # 安装puppeteer
    echo -e "${BLUE}安装Puppeteer...${NC}"
    npm install puppeteer@19.11.1 --no-fund --no-audit --silent 2>&1 | tail -5
    
    # 创建缓存
    if [ -n "$CHROMIUM_PATH" ]; then
        mkdir -p ~/.cache/puppeteer/chrome/linux-1108766
        ln -sf "$CHROMIUM_PATH" ~/.cache/puppeteer/chrome/linux-1108766/chrome 2>/dev/null
        echo "1108766" > ~/.cache/puppeteer/chrome/linux-1108766/revision
    fi
    
    echo -e "${GREEN}✓ Puppeteer修复完成${NC}"
}

# 清理
cleanup() {
    echo -e "${YELLOW}[8/8] 清理...${NC}"
    
    apt-get clean 2>/dev/null
    apt-get autoclean 2>/dev/null
    
    echo -e "${GREEN}✓ 清理完成${NC}"
}

# 显示结果
show_result() {
    echo ""
    echo -e "${GREEN}======================================${NC}"
    echo -e "${GREEN}       重装完成！                    ${NC}"
    echo -e "${GREEN}======================================${NC}"
    echo ""
    
    # Chromium
    if command -v chromium-browser >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Chromium-browser: 已安装${NC}"
    elif command -v chromium >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Chromium: 已安装${NC}"
    elif command -v google-chrome >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Google Chrome: 已安装${NC}"
    else
        echo -e "${RED}✗ 浏览器: 未安装${NC}"
    fi
    
    # Node.js（只检查）
    if command -v node >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Node.js: $(node --version)（未修改）${NC}"
    else
        echo -e "${YELLOW}⚠ Node.js: 未安装（脚本未动）${NC}"
    fi
    
    # Puppeteer
    if [ -d "/root/XRK-Yunzai/node_modules/puppeteer" ]; then
        echo -e "${GREEN}✓ Puppeteer: 已安装${NC}"
    else
        echo -e "${YELLOW}⚠ Puppeteer: 未安装${NC}"
    fi
    
    echo ""
    echo -e "${BLUE}注意：humanity-icon-theme 包已被跳过${NC}"
    echo -e "${BLUE}如需修复，请运行: sudo apt --fix-broken install${NC}"
    echo ""
    echo -e "${GREEN}完成！${NC}"
}

# 主流程
main() {
    echo -e "${BLUE}开始重装...${NC}"
    echo -e "${YELLOW}注意: 不会动Node.js！${NC}"
    echo ""
    
    fix_dpkg_issues
    setup_sources
    clean_browsers
    install_chromium_deps
    install_chromium
    verify_chromium
    fix_puppeteer
    cleanup
    show_result
}

# 执行
main "$@"